package com.yt.lxh.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.yt.lxh.common.result.Result;
import com.yt.lxh.common.result.ResultCodeEnum;
import com.yt.lxh.common.service.CacheService;
import com.yt.lxh.common.utils.AuthContextUtil;
import com.yt.lxh.constant.RedisEnum;
import com.yt.lxh.model.acl.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginAuthInterceptor implements HandlerInterceptor {
    @Autowired
    private CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1 获取请求方法
        //如果请求方式是options 预检请求,直接放行
        String method = request.getMethod();
        if ("OPTIONS".equals(method)){
            System.out.println(1);
            return true;
        }
        //2 从请求头获取token
        String token = request.getHeader("token");
        //3 如果token为空，返回错误提示
        if (StrUtil.isEmpty(token)){
            System.out.println(2);
            responseNoLoginInfo(response);
            return false;
        }
        //4 如果token不为空，拿着token查询redis
        String adminInfoString = cacheService.get(RedisEnum.ADMIN.getMessage() + token);
        //5 如果redis查询不到数据，返回错误提示
        if (StrUtil.isEmpty(adminInfoString)) {
            responseNoLoginInfo(response);
            return false;
        }
        //6 如果redis查询到用户信息，把用户信息放到ThreadLoad里面
        Admin admin = JSON.parseObject(adminInfoString, Admin.class);
        AuthContextUtil.set(admin);
        //7 把redis用户信息数据更新过期时间
        cacheService.expire(RedisEnum.ADMIN.getMessage() +token,
                30,
                TimeUnit.MINUTES);
        //8 放行
        return  true;
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthContextUtil.remove();
    }
}
